package com.wry.service.impl;

import com.wry.dto.StockDeductedDTO;
import com.wry.entity.TStorage;
import com.wry.service.StockApiService;
import com.wry.service.TStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * <h1>  <h1>
 *
 * @author 魏如元
 * @since 2022/10/10
 */
@Service
@Slf4j
public class StockApiServiceImpl implements StockApiService {

    @Resource
    TStorageService tStorageService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void accountDeducted(StockDeductedDTO deductedDTO) {
        final TStorage tStorage = tStorageService.lambdaQuery()
                .eq(TStorage::getProductId, deductedDTO.getProductId())
                .one();
        if (Objects.isNull(tStorage)){
            log.warn("productId = {} is null", deductedDTO.getProductId());
            return;
        }
        // 已用库存加
        int used = tStorage.getUsed() + deductedDTO.getCount();
        // 可用库存减
        int residue = tStorage.getResidue() - deductedDTO.getCount();

        tStorageService.lambdaUpdate()
                .set(TStorage::getUsed, used)
                .set(TStorage::getResidue, residue)
                .update(tStorage);
    }
}
